<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <label for="input">输入</label>
      <input title="input" id="input" name="input" type="text" />
      <button id="send">发送</button>
    </div>
    <div>
      <h5>接受到的消息:</h5>
      <div>当前用户：<input title="user" disabled id="user" type="text" /></div>
      <ol id="list"></ol>
    </div>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
      // 生成随机数作为用户名
      var array = new Uint32Array(1);
      window.crypto.getRandomValues(array);
      var randomInt = array[0] % 1000;
      $('#user').val(randomInt);

      function addList({ user, message }) {
        if (user === randomInt) {
          user = user + '(我)';
        }
        $('#list').append(`<li>用户${user}: ${message}</li>`);
      }

      // 连接至广播频道
      const bc = new BroadcastChannel('test_channel');
      function addMessage(user, message) {
        bc.postMessage({ user, message });
        addList({ user, message });
      }
      bc.onmessage = (event) => {
        addList(event.data);
      };
      if (!(window.top === window)) {
        window.open('./BroadcastChannelAPI.html');
      }
      addMessage(randomInt, 'Hello, BroadcastChannel, I am ' + randomInt);
      $('#send').click(function () {
        var message = $('#input').val();
        addMessage(randomInt, message);
        $('#input').val('');
      });
    </script>
  </body>
</html>
